<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ include file="../base/head.jsp" %>
<html>
<head>
    <title>ajax数据参数请求格式</title>
</head>
<body>

    <form>
        <input id="a1" type="text" value="x" name="a1"><br>
        <input id="a2" type="text" value="y" name="a2"><br>
        <input id="a3" type="text" value="z" name="a3"><br>
        <select id="ax" name="ax">
            <option value="0">选项1</option>
            <option value="1">选项2</option>
        </select><br>
        <input id="submit" type="button" value="提交" name="submit">
    </form>

    <button>序列化表单值</button>
    <div id="results"></div>
</body>

<script type="text/javascript">
    //得到搜索框数据
    function getFromData() {
        var d = {};
        var t = $('form').serializeArray();
        //t的值为[{name: "a1", value: "xx"}, {name: "a2", value: "xx"}...]
        $.each(t, function(i, field) {
            d[field.name] = field.value;
        });
        //d的值为{"a1":"x","a2":"y","a3":"z","ax":"0"}
        return d;
    }

    //发送ajax请求(第一种方式，推荐)：1.contentType 可以不填 2.发送数据为json对象
    let obj=getFromData();
    alert(JSON.stringify(obj));
    $.ajax({
        url: "search_data_detail.action",
        type: "post",
        dataType:'json',
        data: {"jsonData":JSON.stringify(obj)},
        success: function (json) {

        }
    });
    //发送ajax请求（第二种方式）：1.必须填写contentType 2.发送数据为json字符串
    $.ajax({
        url: "search_data_detail2.action",
        type: "post",
        dataType:'json',
        contentType : 'application/json;charset=utf-8',
        data:  JSON.stringify(obj),
        success: function (json) {

        }
    });

</script>
</html>
